package org.arain.baseii.system.user;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.arain.baseii.aspect.annotation.SystemExceptionLog;
import org.arain.baseii.aspect.annotation.SystemServiceLog;
import org.arain.baseii.common.CommonServiceImpl;
import org.arain.baseii.exception.UseException;
import org.arain.baseii.grid.GridData;
import org.arain.baseii.grid.QueryParam;
import org.arain.baseii.mapper.SysAttachmentsMapper;
import org.arain.baseii.mapper.SysRoleMapper;
import org.arain.baseii.mapper.SysUserAttachmentsMapper;
import org.arain.baseii.mapper.SysUserMapper;
import org.arain.baseii.mapper.SysUserRoleMapper;
import org.arain.baseii.pojo.SysAttachments;
import org.arain.baseii.pojo.SysAttachmentsExample;
import org.arain.baseii.pojo.SysRole;
import org.arain.baseii.pojo.SysRoleExample;
import org.arain.baseii.pojo.SysUser;
import org.arain.baseii.pojo.SysUserAttachmentsKey;
import org.arain.baseii.pojo.SysUserExample;
import org.arain.baseii.pojo.SysUserExample.Criteria;
import org.arain.baseii.system.role.SysRoleDto;
import org.arain.baseii.utils.AppUtils;
import org.arain.baseii.utils.ArainResult;
import org.arain.baseii.utils.DictUtil;
import org.arain.baseii.utils.IDUtil;
import org.arain.baseii.utils.PasswordCheck;
import org.arain.baseii.pojo.SysUserRoleExample;
import org.arain.baseii.pojo.SysUserRoleKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;

/**
 * 
* <p>Title:SysRoleController </p>
* @author Arain
* @date2017年8月31日
 */
@Service
@Transactional
public class SysUserServiceImpl extends CommonServiceImpl<SysUserDto> implements SysUserService{
	@Autowired
	private SysUserMapper sysUserMapper;
	@Autowired
	private SysRoleMapper sysRoleMapper;
	@Autowired
	private SysUserRoleMapper sysUserRoleMapper;
	@Autowired
	private SysAttachmentsMapper sysAttachmentsMapper;
	@Autowired
	private SysUserAttachmentsMapper sysUserAttachmentsMapper;
	@Value("${ADMIN}")
	private Long admin;
	@Value("${PASSWORD}")
	private String password;
	
	@Override
	public String load_grid(QueryParam param,Short userType) {
		SysUserDto dto = new SysUserDto();
		try {
			dto = this.jsonToObject(param.getFilterRules(),dto);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		JSONArray array = new JSONArray();
		SysUserExample example = new SysUserExample();
		Criteria criteria = example.createCriteria();
		if(StringUtils.isNotBlank(param.getOrder()) && StringUtils.isNotBlank(param.getSort())) {
			example.setOrderByClause(param.getSort()+" "+param.getOrder());
		}
		if(StringUtils.isNotBlank(dto.getUsername())) {
			criteria.andUsernameLike("%"+dto.getUsername()+"%");
		}
		if(StringUtils.isNotBlank(dto.getPhone())) {
			criteria.andPhoneLike("%"+dto.getPhone()+"%");
		}
		if(StringUtils.isNotBlank(dto.getEnabled())) {
			criteria.andEnabledEqualTo(Short.valueOf(dto.getEnabled()));
		}
		criteria.andUsertypeEqualTo(userType).andIdNotEqualTo(AppUtils.getUserId());
		
		PageHelper.startPage(param.getPage(), param.getRows());
		List<SysUser> list = sysUserMapper.selectByExample(example);
		int countByExample = sysUserMapper.countByExample(example);
		for (SysUser sysUser : list) {
			JSONObject object = new JSONObject();
			object.put("id", sysUser.getId());
			object.put("username", sysUser.getUsername());
			object.put("realname", sysUser.getRealname());
			object.put("email", sysUser.getEmail());
			object.put("phone", sysUser.getPhone());
			object.put("enabled", DictUtil.load_dict(sysUser.getEnabled()+"", "ENABLED_").getDispaly());
			
			array.add(object);
		}
		GridData data = new GridData();
		data.setTotal(countByExample);
		data.setRows(array);
		return GridData.gridToJson(data);
	}
	
	@CacheEvict(value="shirocache",allEntries=true,beforeInvocation=true)
	@Override
	@SystemExceptionLog(description="保存")
	@SystemServiceLog(description="保存")
	public ArainResult save_01(SysUserDto dto) {
		if(StringUtils.isNotBlank(dto.getId())) {
			SysUser user = new SysUser();
			AppUtils.copyProperties(user, dto);
			sysUserMapper.updateByPrimaryKey(user);
			
			SysUserRoleExample example = new SysUserRoleExample();
			example.createCriteria().andUserIdEqualTo(user.getId());
			sysUserRoleMapper.deleteByExample(example);
			
			for (String roleid : dto.getRoleId()) {
				SysUserRoleKey record = new SysUserRoleKey();
				
				record.setRoleId(Long.valueOf(roleid));
				record.setUserId(user.getId());
				
				sysUserRoleMapper.insert(record);
			}
			return ArainResult.ok();
		} else {
			SysUserExample example = new SysUserExample();
			example.createCriteria().andUsernameEqualTo(dto.getUsername());
			List<SysUser> list = sysUserMapper.selectByExample(example);
			if(list != null && list.size() > 0) {
				throw new UseException("用户名已存在");
			}
			SysUser user = new SysUser();
			dto.setId(IDUtil.genId());
			dto.setExpired(PasswordCheck.checkPassword(password)+"");
			dto.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
			AppUtils.copyProperties(user, dto);
			sysUserMapper.insert(user);
			for (String roleid : dto.getRoleId()) {
				SysUserRoleKey record = new SysUserRoleKey();
				
				record.setRoleId(Long.valueOf(roleid));
				record.setUserId(user.getId());
				sysUserRoleMapper.insert(record);
			}
			return ArainResult.ok();
		}
		
	}

	@Override
	public SysUserDto load_01(SysUserDto dto) {
		SysUser user = sysUserMapper.selectByPrimaryKey(Long.valueOf(dto.getId()));
		AppUtils.copyProperties(dto, user);
		return dto;
	}

	@Override
	public List<SysRoleDto> load_check_role(SysUserDto userDto) {
		SysRoleExample example = new SysRoleExample();
		example.createCriteria().andEnabledEqualTo((short) 1).andOrgidEqualTo(AppUtils.getOrgId()).andIdNotEqualTo(admin).andOrgidEqualTo(AppUtils.getOrgId());
		List<SysRole> list = sysRoleMapper.selectByExample(example);
		
		List<SysRoleDto> roleDtos = new ArrayList<>();
		for (SysRole sysRole : list) {
			SysRoleDto dto = new SysRoleDto();
			AppUtils.copyProperties(dto, sysRole);
			roleDtos.add(dto);
		}
		SysUserRoleExample key = new SysUserRoleExample();
		if(StringUtils.isNotBlank(userDto.getId())) {
			key.createCriteria().andUserIdEqualTo(Long.valueOf(userDto.getId()));
			List<SysUserRoleKey> keyList = sysUserRoleMapper.selectByExample(key);
			for (SysRoleDto sysRoleDto : roleDtos) {
				in:for (SysUserRoleKey dtoKey : keyList) {
					if(sysRoleDto.getId().toString().equals(dtoKey.getRoleId().toString())) {
						sysRoleDto.setChecked("checked");
						break in;
					}
				}
			}
		}
		return roleDtos;
	}

	@Override
	public ArainResult save_myself(SysUserDto dto,HttpServletRequest request) {
		SysUser user = sysUserMapper.selectByPrimaryKey(Long.valueOf(dto.getId()));
		if(!user.getPassword().equals(DigestUtils.md5DigestAsHex(dto.getOldPassword().getBytes()))) {
			throw new UseException("旧密码错误");
		}
		user.setExpired((short) PasswordCheck.checkPassword(dto.getPassword()));
		user.setPassword(DigestUtils.md5DigestAsHex(dto.getPassword().getBytes()));
		sysUserMapper.updateByPrimaryKey(user);
	
		return ArainResult.ok();
	}

	@Override
	public String load_head_image(Long id) {
		SysUser user = sysUserMapper.selectByPrimaryKey(id);
		SysAttachmentsExample example = new SysAttachmentsExample();
		if(user.getHead()==null) {
			return "";
		}
		example.createCriteria().andEnabledEqualTo(1).andIdEqualTo(user.getHead());
		List<SysAttachments> list = sysAttachmentsMapper.selectByExample(example);
		if(list!=null && list.size()>0) {
			SysAttachments attachments = list.get(0);
			return attachments.getServicePath()+attachments.getAppName()+attachments.getAttachmentPath();
		}
		return "";
		
	}

	@Override
	public ArainResult save_head(SysUserDto dto, HttpServletRequest request) {
		SysUser user = sysUserMapper.selectByPrimaryKey(Long.valueOf(dto.getId()));
		if(user.getHead()!=null) {
			if(user.getHead().toString().equals(dto.getHead())) {
				throw new UseException("头像未发生该表改变！");
			}
		}
		user.setHead(Long.valueOf(dto.getHead()));
		sysUserMapper.updateByPrimaryKey(user);
		SysUserAttachmentsKey attachmentsKey = new SysUserAttachmentsKey();
		attachmentsKey.setUserId(user.getId());
		attachmentsKey.setAttachmentsId(Long.valueOf(dto.getHead()));
		sysUserAttachmentsMapper.insert(attachmentsKey);
		
		SysAttachments attachments = sysAttachmentsMapper.selectByPrimaryKey(Long.valueOf(dto.getHead()));
		attachments.setEnabled(1);
		sysAttachmentsMapper.updateByPrimaryKey(attachments);		
		return ArainResult.ok();
	}

	@Override
	public String load_rank() {
		SysUser user = sysUserMapper.selectByPrimaryKey(AppUtils.getUserId());
		return DictUtil.load_dict(user.getExpired()+"", "RANK").getDispaly();
	}
}
